from bs4 import BeautifulSoup

html_text = """<html>
    <head>
        <title>这是一个构造的测试页面</title>
    </head>
    <body>
        <p class="title">
            <b>页面标题</b>
        </p>
        <p class="story">这里给了几个网站：
			<a href="https://www.baidu.com" class="baidu index" id="link1">百度</a>,
			<a href="https://www.taobao.com" class="taobao" id="link2">淘宝</a>,
			<a href="https://www.jd.com" class="jindong" id="link3">京东</a>.
			<div>
				<a href="https://www.bilibili.com/" class="bilibili index" id="link4">哔哩哔哩</a>
			</div>
        </p>

        <p class="story">...</p>
    </body>
</html>"""

# 实例化一个解析对象
soup = BeautifulSoup(html_text, "lxml")  # 第一个参数：需要解析的数据，第二个参数：使用的解析器
# print(soup)
# print(type(soup))
# # 格式化输入html字符串
# html = soup.prettify()
# print(html)
# print(type(html))

# # 获取a标签，标签对象，获取的是soup这个解析对象里面第一个a标签
# a_soup = soup.a
# print(a_soup)
# print(type(a_soup))
# print(a_soup.prettify())

# # 获取标签内文本
# a_soup = soup.a
# a_text = a_soup.text
# print(a_soup)
# print(a_text)

# # 获取标签内属性，获取到的是一个字典，而且class属性的值是一个列表
# print(soup.a)
# print(soup.a.attrs)

# # 获取指定属性值，参照字典取值方式
# print(soup.a)
# print(soup.a.attrs)
# print(soup.a.attrs.get('id'))
# print(soup.a.attrs["class"])

# # 获取子节点，返回的是一个可迭代对象，把换行符等都算作了子节点元素放到了可迭代对象中
# p_soup = soup.p
# print(p_soup)
# print("__________________________________")
# p_chilren = p_soup.children
# for i in p_chilren:
#     print(i)
#     print("--------------------------------------")

# # 获取标签内部所有的元素，获取的是一个列表
# p_soup = soup.p
# print(p_soup)
# print("-------------------------------------")
# print(p_soup.contents)
# print(type(p_soup.contents))

# # 获取标签的父标签
# a_soup = soup.a
# parent_soup = a_soup.parent
# print(parent_soup)

# # 获取所有上级节点
# a_soup = soup.a
# parent_soups = a_soup.parents
# print(parent_soups)
# for i in parent_soups:
#     print(i)
#     print("**********************************************")